package com.liumuxian.exam.web.controller;

import com.liumuxian.exam.client.OrdersClient;
import com.liumuxian.exam.pojo.ExamClassify;
import com.liumuxian.exam.service.ExamClassifyService;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/examclassify")
public class ExamClassifyController {
    @Autowired
    private ExamClassifyService examClassifyService;
    @Autowired
    private OrdersClient ordersClient;
    @Autowired
    private JwtUtil jwtUtil;
    //注入request
    @Autowired
    private HttpServletRequest request;

    @GetMapping("{said}")
    public Result list(@PathVariable String said){
        List<ExamClassify> examClassify = examClassifyService.findAll();
        HashSet<String> id = new HashSet<>();
        examClassify.forEach(ec ->id.add(said+ec.getId()));
        Claims claims= (Claims) request.getAttribute("user_claims");
        if(claims==null){
            throw new RuntimeException("请先登录！");
        }
        Result result =  ordersClient.shoppurc(id,claims.getId());
        if(result!=null && result.getCode() == 0){
          Map<String,String> map = (Map<String, String>) result.getData();
            examClassify.forEach(ec -> {
                Boolean fig= Boolean.parseBoolean(map.get(said+ec.getId()));
                if(fig){
                    ec.setType(2);
                }
            });
        }

        return new Result(true, StatusCode.OK,"查询成功！",examClassify);
    }
    @PostMapping("/save")
    public Result save(@RequestBody ExamClassify examClassify){
        examClassifyService.save(examClassify);
        return new Result(true, StatusCode.OK,"保存成功！");
    }
    @PostMapping("/update")
    public Result update(@RequestBody ExamClassify examClassify){
        examClassifyService.update(examClassify);
        return new Result(true, StatusCode.OK,"修改成功！");
    }
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable String id){
        examClassifyService.delete(id);
        return new Result(true, StatusCode.OK,"删除成功！");
    }
    @GetMapping("/list")
    public Result findAllGesTate(){
        List<ExamClassify> examClassifyList = examClassifyService.findAllGesTate(null,null,0);
        return new Result(true, StatusCode.OK,"查询成功！",examClassifyList);
    }
    @GetMapping("/{id}")
    public Result findById(@PathVariable String id){
        ExamClassify examClassifyList = examClassifyService.findById(id);
        return new Result(true, StatusCode.OK,"查询成功！",examClassifyList);
    }
}
